package com.ruoyi.web.controller.app;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.JwtResultEnums;
import com.ruoyi.common.exception.ResultException;
import com.ruoyi.framework.jwt.annotation.JwtPermissions;
import com.ruoyi.framework.jwt.config.properties.JwtProjectProperties;
import com.ruoyi.framework.jwt.utlis.JwtUtil;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/app")
public class AppLoginController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private JwtProjectProperties properties;

    @Autowired
    private SysPasswordService passwordService;

    @PostMapping("/api/login")
    @ResponseBody
    public AjaxResult auth(String username, String password) {
        // 根据用户名获取系统用户数据
        SysUser user = sysUserService.selectUserByLoginName(username);
        if (user == null) {
            throw new ResultException(JwtResultEnums.AUTH_REQUEST_ERROR);
        } else if (user.getStatus().equals("1")) {
            throw new ResultException(JwtResultEnums.AUTH_REQUEST_LOCKED);
        } else {
            // 对明文密码加密处理
            String encrypt = passwordService.encryptPassword(username, password, user.getSalt());
            // 判断密码是否正确
            if (encrypt.equals(user.getPassword())) {
                String token = null;
                try {
                    token = JwtUtil.getToken(username, properties.getSecret(), properties.getExpired());
                    // 头部添加 Authorization 字段
                    // token = "Bearer "+token
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    throw  new ResultException(JwtResultEnums.AUTH_SERVER_ERROR);
                }
                return AjaxResult.success("成功",token);
            } else {
                throw new ResultException(JwtResultEnums.AUTH_REQUEST_ERROR);
            }
        }
    }


    @PostMapping("/api/user")
    @JwtPermissions
    @ResponseBody
    public AjaxResult userinfo(HttpServletRequest request) {
        // 根据用户名获取系统用户数据

        SysUser user = JwtUtil.parseToken(JwtUtil.getRequestToken(request));
        SysUser lastUser = sysUserService.selectUserByLoginName(user.getLoginName());
        return AjaxResult.success("成功",lastUser);
    }
}
